import { useMemo, useState } from "react";
/**
 * 入参
回调函数:Function：返回需要缓存的值
依赖项:Array：依赖项发生变化时，回调函数会重新执行(执行时机跟useEffect类似)
返回值:
返回值：返回需要缓存的值(返回之后就不是函数了)
 */
export function UseMemoDemo() {
  const [search, setSearch] = useState("");
  const [goods, setGoods] = useState([
    { id: 1, name: "苹果", price: 10, count: 1 },
    { id: 2, name: "香蕉", price: 20, count: 1 },
    { id: 3, name: "橘子", price: 30, count: 1 },
  ]);
  const handleAdd = (id: number) => {
    setGoods(
      goods.map((item) =>
        item.id === id ? { ...item, count: item.count + 1 } : item
      )
    );
  };
  const handleSub = (id: number) => {
    setGoods(
      goods.map((item) =>
        item.id === id ? { ...item, count: item.count - 1 } : item
      )
    );
  };

  // 未使用useMemo，每次输入都会重新计算，因为组件每次更新都会重新执行
  const total = () => {
    console.log("total");
    //例如很复杂的计算逻辑
    return goods.reduce((total, item) => total + item.price * item.count, 0);
  };

  // 使用useMemo，只有当依赖项发生变化时，才会重新计算
  const total2 = useMemo(() => {
    console.log("total2");
    //例如很复杂的计算逻辑
    return goods.reduce((total, item) => total + item.price * item.count, 0);
  }, [goods]);

  return (
    <div>
      <h1>useMemo使用=====》》》》》》》</h1>
      <input
        placeholder="请输入商品名称"
        type="text"
        value={search}
        onChange={(e) => setSearch(e.target.value)}
      />
      <table border={1} cellPadding={5} cellSpacing={0}>
        <thead>
          <tr>
            <th>商品名称</th>
            <th>商品价格</th>
            <th>商品数量</th>
          </tr>
        </thead>
        <tbody>
          {goods.map((item) => (
            <tr key={item.id}>
              <td>{item.name}</td>
              <td>{item.price * item.count}</td>
              <td>
                <button onClick={() => handleAdd(item.id)}>+</button>
                <span>{item.count}</span>
                <button onClick={() => handleSub(item.id)}>-</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <h2>总价：{total()}</h2>
      {/* 返回之后就不是函数了，而是缓存值 */}
      <h2>总价：{total2}</h2>
    </div>
  );
}
